<script lang="ts">
import dayjs from 'dayjs';
</script>

<script lang="ts" setup>
const emit = defineEmits<{
  'update:startTime': [value: number];
  'update:endTime': [value: number];
}>();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const value = ref('current');
const options = computed(() => {
  const regTime = userInfo.value?.reg_time ? dayjs(userInfo.value.reg_time) : null;
  const monthOptions = [];
  const regMonth = regTime ? regTime.startOf('month') : null;
  const currentMonth = dayjs().startOf('month');
  const monthDiff = regMonth ? currentMonth.diff(regMonth, 'month') : 5;
  const maxMonths = Math.min(5, monthDiff);

  for (let i = 0; i <= maxMonths; i++) {
    const monthInfo = getMonthInfo(i === 0 ? 0 : -i);
    monthOptions.push({
      value: i === 0 ? 'current' : `last${i}`,
      label: monthInfo.start,
    });
  }

  return monthOptions;
});

function getMonthInfo(monthOffset = 0) {
  const date = dayjs().add(monthOffset, 'month');
  const month = date.month() + 1;
  const year = date.year();
  const startOfMonth = date.startOf('month').toDate();
  const endOfMonth = date.endOf('month').toDate();
  const start = date.format('YYYY-MM');

  return {
    month,
    startOfMonth,
    endOfMonth,
    start,
  };
}
// reg_time  options选项不能超过注册时间   1737800355725
function handleChange(value: string) {
  const monthOffset = value === 'current' ? 0 : -Number.parseInt(value.replace('last', ''));
  const monthInfo = getMonthInfo(monthOffset);

  emit('update:startTime', dayjs(monthInfo.startOfMonth).utc(true).valueOf());
  emit('update:endTime', dayjs(monthInfo.endOfMonth).utc(true).valueOf());
}
</script>

<template>
  <ASelect
    v-model:value="value"
    class="antd-cover__Select-3d-gray"
    :options="options"
    inputReadOnly
    @change="handleChange"
  />
</template>
